package com.gitee.sop.gateway.service.dubbo;

import com.gitee.sop.gateway.common.ApiInfoDTO;
import com.gitee.sop.gateway.common.enums.StatusEnum;
import com.gitee.sop.gateway.dao.entity.ApiInfo;
import com.gitee.sop.gateway.dao.mapper.ApiInfoMapper;
import com.gitee.sop.gateway.service.manager.ApiManager;
import com.gitee.sop.gateway.util.CopyUtil;
import com.gitee.sop.support.service.ApiRegisterService;
import com.gitee.sop.support.service.dto.RegisterDTO;
import com.gitee.sop.support.service.dto.RegisterResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * @author 六如
 */
@Slf4j
@DubboService
public class ApiRegisterServiceImpl implements ApiRegisterService {

    private static final int REG_SOURCE_SYS = 1;

    @Autowired
    private ApiManager apiManager;

    @Autowired
    private ApiInfoMapper apiInfoMapper;

    @Override
    public RegisterResult register(RegisterDTO registerDTO) {
        log.info("收到接口注册, registerDTO={}", registerDTO);

        try {
            ApiInfoDTO apiInfoDTO = CopyUtil.copyBean(registerDTO, ApiInfoDTO::new);
            apiInfoDTO.setStatus(StatusEnum.ENABLE.getValue());

            ApiInfo apiInfo = apiInfoMapper.getByNameVersion(apiInfoDTO.getApiName(), apiInfoDTO.getApiVersion());

            if (apiInfo == null) {
                apiInfo = new ApiInfo();
            } else {
                check(apiInfo, registerDTO);
            }
            CopyUtil.copyPropertiesIgnoreNull(apiInfoDTO, apiInfo);
            apiInfo.setRegSource(REG_SOURCE_SYS);
            // 保存到数据库
            apiInfoMapper.saveOrUpdate(apiInfo);
            apiInfoDTO.setId(apiInfo.getId());
            // 保存到缓存
            apiManager.save(apiInfoDTO);
            return RegisterResult.success();
        } catch (Exception e) {
            log.error("接口注册失败, registerDTO={}", registerDTO, e);
            return RegisterResult.error(e.getMessage());
        }
    }

    private void check(ApiInfo apiInfo, RegisterDTO registerDTO) {
        if (!Objects.equals(apiInfo.getApplication(), registerDTO.getApplication())) {
            throw new RuntimeException("接口[" + registerDTO + "]已存在于[" + apiInfo.getApplication() + "]应用中.必须保证接口全局唯一");
        }
    }

}
